package com.deeper.customview.ui.c7.demo.c07d03;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Scroller;

public class BaseScrollerViewGroup extends ViewGroup {


    private Scroller scroller;
    private Button btnAndroid;


    public BaseScrollerViewGroup(Context context) {
        super(context);
    }


    public BaseScrollerViewGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public BaseScrollerViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        scroller = new Scroller(context);
        btnAndroid = new Button(context);
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        btnAndroid.setText("Android 自定义组件");
        this.addView(btnAndroid, layoutParams);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        btnAndroid.layout(10, 10, btnAndroid.getMeasuredWidth() + 10,
                btnAndroid.getMeasuredHeight() + 10);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST
                || MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            throw new IllegalStateException("Must be MeasureSpec.EXACTLY");
        }

        measureChildren(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
                MeasureSpec.getSize(heightMeasureSpec));
    }


    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            //设置容器内组件的新位置
            this.scrollTo(scroller.getCurrX(), scroller.getCurrY());
            //重绘以刷新产生动画
            postInvalidate();
        }
    }

    /**
     * 开始滚动，外部调用
     */
    public void start() {
        //从当前位置开始滚动，
        scroller.startScroll(this.getScrollX(), this.getScrollY(), -900, 0, 10000);
        //重绘
        postInvalidate();
    }

    /**
     * 取消滚动，直接到达目的地
     */
    public void abort() {
        scroller.abortAnimation();
    }
}
